package nyx.service.book;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import nyx.dao.book.BookMapper;
import nyx.dao.reader.ReaderMapper;
import nyx.dao.record.RecordMapper;
import nyx.pojo.Book;
import nyx.pojo.Record;


@Service("bookService")
public class BookServiceImpl implements BookService {

	
	@Autowired
	private BookMapper bookMapper;
	@Autowired
	private RecordMapper recordMapper;
	@Autowired
	private ReaderMapper readerMapper;
	@Override
	public List<Book> getAll(int pageIndex, int pageSize) {
		int beginIndex = (pageIndex - 1) * pageSize;
		if(beginIndex < 0){
			beginIndex = 0;
		}
		
		return bookMapper.queryAll(beginIndex, pageSize);
	}

	@Override
	public int getPageCount(int pageSize) {
		int totalCount = bookMapper.totalCount();
		return totalCount % pageSize == 0 ? totalCount / pageSize : totalCount
				/ pageSize + 1;
		
	}

	@Override
	public Book getOne(int bId) {
		return bookMapper.queryOneById(bId);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int borrowBook(int readerId, int bId) {
		int no = -1;
		int i = 0;
		try {
			i = readerMapper.updateCanBorrowCount(readerId, no);
			if(i<=0){
				throw new RuntimeException("修改可借数量失败");
			}
			i=readerMapper.updateCanBorrowCount(bId, no);
			if(i<=0){
				throw new RuntimeException("修改图书数量失败");
			}
			Record record = new Record();
			record.setbId(bId);
			record.setReaderId(readerId);
			i = recordMapper.insert(record);
			
			if(i<=0){
				throw new RuntimeException("插入借书记录失败");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return i;
	}
	
	@Transactional(propagation = Propagation.REQUIRED)

	@Override
	public int returnBook(int readerId, int bid) {
		int no = 1;
		int i = 0;
		try {
			i = recordMapper.updateReturnDate(readerId, bid);
			if(i<=0){
				throw new RuntimeException("修改归还日期失败");
			}
			i = readerMapper.updateCanBorrowCount(readerId, no);
			if(i<=0){
				throw new RuntimeException("修改可借数量失败");
			}
			i = bookMapper.updateBookCount(bid, no);
			if(i<=0){
				throw new RuntimeException("修改图书数量失败");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return i;
	}

}
